<template>
  <div class="workforce-list">
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="年月">
          <el-date-picker
            v-model="searchForm.yearMonth"
            type="month"
            format="YYYY-MM"
            value-format="YYYY-MM"
            placeholder="选择年月"
            @change="handleDateChange"
            clearable
          />
        </el-form-item>
        <el-form-item label="上/下半月">
          <el-select 
            v-model="searchForm.halfMonth" 
            placeholder="请选择" 
            @change="handleHalfMonthChange" 
            style="width: 160px"
            clearable
          >
            <el-option label="上半月(1-15号)" value="first" />
            <el-option label="下半月(16-月末)" value="second" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleAdd">新增排班</el-button>
          <el-button @click="refreshData">刷新数据</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <!-- 固定列 -->
      <el-table-column type="index" label="序号" width="60" fixed="left" />
      <el-table-column prop="nurseName" label="护士姓名" width="120" fixed="left" />
      
      <!-- 动态日期列 -->
      <template v-for="day in displayDays" :key="day">
        <el-table-column :prop="'day_' + day" :label="formatColumnLabel(day)" min-width="120">
          <template #default="scope">
            <template v-if="scope.row && 'day_' + day in scope.row">
              <span :class="getShiftClass(scope.row['day_' + day])">
                {{ scope.row['day_' + day] || '-' }}
              </span>
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
      </template>

      <!-- 操作列 -->
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 搜索表单
const searchForm = reactive({
  yearMonth: dayjs().format('YYYY-MM'),
  halfMonth: 'first'
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const displayDays = ref([])

// 计算显示的天数
const calculateDisplayDays = () => {
  if (!searchForm.yearMonth || !searchForm.halfMonth) return []
  
  const [year, month] = searchForm.yearMonth.split('-')
  const daysInMonth = dayjs(`${year}-${month}`).daysInMonth()
  const startDay = searchForm.halfMonth === 'first' ? 1 : 16
  const endDay = searchForm.halfMonth === 'first' ? 15 : daysInMonth
  
  // 确保生成的天数范围是正确的
  const days = []
  for (let i = startDay; i <= endDay; i++) {
    days.push(i)
  }
  
  console.log(`计算日期范围: ${searchForm.yearMonth}, ${searchForm.halfMonth}, 开始:${startDay}, 结束:${endDay}, 天数:${days.length}, stage:${getStageValue(searchForm.halfMonth)}`)
  return days
}

// 格式化列标签
const formatColumnLabel = (day) => {
  if (!searchForm.yearMonth) return day + '日'
  
  try {
    const dateStr = `${searchForm.yearMonth}-${day.toString().padStart(2, '0')}`
    const date = dayjs(dateStr)
    
    if (!date.isValid()) {
      console.error(`无效日期: ${dateStr}`)
      return `${day}日`
    }
    
    const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.day()]
    return `${day}日(${weekDay})`
  } catch (error) {
    console.error('格式化日期错误:', error)
    return `${day}日`
  }
}

// 获取班次样式
const getShiftClass = (shift) => {
  if (!shift || shift === '-') return ''
  
  const classMap = {
    '早班': 'shift-morning',
    '中班': 'shift-middle',
    '晚班': 'shift-night',
    '休息': 'shift-rest'
  }
  return classMap[shift] || ''
}

// 获取路由参数值转换为stage
const getStageValue = (halfMonth) => {
  return halfMonth === 'first' ? 1 : 2
}

// 查询
const handleSearch = () => {
  if (!searchForm.yearMonth || !searchForm.halfMonth) {
    ElMessage.warning('请选择年月和上/下半月')
    return
  }
  displayDays.value = calculateDisplayDays()
  getWorkforceList()
}

// 处理日期变化
const handleDateChange = () => {
  console.log('日期变化:', searchForm.yearMonth)
  displayDays.value = calculateDisplayDays()
  getWorkforceList()
}

// 处理上下半月变化
const handleHalfMonthChange = () => {
  console.log('上/下半月变化:', searchForm.halfMonth)
  displayDays.value = calculateDisplayDays()
  getWorkforceList()
}

// 获取排班数据
const getWorkforceList = async () => {
  loading.value = true
  // 清空之前的数据
  tableData.value = []
  
  try {
    if (!searchForm.yearMonth) {
      ElMessage.warning('请选择年月')
      return
    }

    const [year, month] = searchForm.yearMonth.split('-')
    let stage = searchForm.halfMonth ? getStageValue(searchForm.halfMonth) : 0
    
    console.log('获取排班数据参数:', {
      year,
      month,
      stage
    })
    
    // 使用查询字符串传参
    const response = await proxy.http.get(`/api/WorkforceController/GetWorkforce?year=${year}&month=${month}&stage=${stage}`)
    
    // 检查请求状态
    if (!response || !response.status) {
      ElMessage.error(response?.message || '获取排班数据失败')
      tableData.value = []
      return
    }
    
    // 确保 response.data 是数组且有数据
    if (!Array.isArray(response.data)) {
      ElMessage.warning('没有找到排班数据')
      tableData.value = []
      return
    }
    
    if (response.data.length === 0) {
      ElMessage.warning('当前时间段没有排班数据')
      return
    }

    console.log('获取到的原始数据:', response.data)

    // 使用 Map 来按护士分组
    const nurseMap = new Map()
    
    response.data.forEach(item => {
      if (!item || !item.nurseCode) return
      
      // 如果这个护士已经存在，就更新排班信息
      if (nurseMap.has(item.nurseCode)) {
        const nurseData = nurseMap.get(item.nurseCode)
        nurseData[`day_${item.stage}`] = item.classGroup || '-'
      } else {
        // 如果是新护士，创建新记录
        const nurseData = {
          id: item.id,
          nurseCode: item.nurseCode,
          nurseName: item.nurseName ? item.nurseName.trim() : '-', // 去除多余的空格
          year: item.year,
          month: item.month
        }
        
        // 初始化所有日期为 '-'
        displayDays.value.forEach(day => {
          nurseData[`day_${day}`] = '-'
        })
        
        // 设置当前排班
        nurseData[`day_${item.stage}`] = item.classGroup || '-'
        
        nurseMap.set(item.nurseCode, nurseData)
      }
    })
    
    // 转换 Map 为数组
    tableData.value = Array.from(nurseMap.values())

    // 调试输出
    console.log('显示天数:', displayDays.value)
    console.log('表格数据:', tableData.value)

  } catch (error) {
    console.error('获取排班数据错误:', error)
    ElMessage.error('获取排班数据失败：' + (error.message || '未知错误'))
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  router.push('/WorkforceManagement')
}

// 编辑
const handleEdit = (row) => {
  console.log('编辑排班:', row)
  
  // 获取当前选择的stage值（1或2）
  const stage = searchForm.halfMonth ? getStageValue(searchForm.halfMonth) : 0
  
  router.push({
    path: '/WorkforceManagementUpd',
    query: {
      nurseCode: row.nurseCode,
      year: row.year,
      month: row.month,
      stage: stage // 传递数字值1或2
    }
  })
}

// 刷新数据
const refreshData = () => {
  displayDays.value = calculateDisplayDays()
  getWorkforceList()
}

// 初始化
onMounted(() => {
  // 如果没有设置默认值，设置当前年月和上半月
  if (!searchForm.yearMonth) {
    searchForm.yearMonth = dayjs().format('YYYY-MM')
  }
  if (!searchForm.halfMonth) {
    searchForm.halfMonth = 'first'
  }
  
  console.log('初始化搜索条件:', searchForm)
  displayDays.value = calculateDisplayDays()
  getWorkforceList()
})
</script>

<style scoped>
.workforce-list {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.shift-morning {
  color: #67C23A;
}

.shift-middle {
  color: #E6A23C;
}

.shift-night {
  color: #409EFF;
}

.shift-rest {
  color: #909399;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-table td) {
  padding: 8px 0;
}

.el-button {
  margin-right: 10px;
}
</style>
